package record

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func RegisterRoute(r *gin.RouterGroup) {
	g := r.Group("/record")
	g.GET("", func(c *gin.Context) {
		array, err := FindAll()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"data": array,
		})
	})
	g.POST("", func(c *gin.Context) {
		v := &Record{}
		if err := c.ShouldBindJSON(v); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}
		if err := InsertOrUpdate(v); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"message": "success",
		})
	})
	g.DELETE("", func(c *gin.Context) {
		var id struct {
			ID int64 `json:"id"`
		}
		if err := c.ShouldBindJSON(&id); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}
		if err := Delete(&Record{Id: id.ID}); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"message": "success",
		})
	})
}
